﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ServiceModel;
using Caliburn.Micro;

using TheKitchen.Client.Commanding;

namespace TheKitchen.Client.Services
{
    public class CommandAgent : ICommandAgent
    {
        private readonly IBusyService busyService;
        private readonly IEventAggregator eventAggregator;
        public Uri CommandServiceUri = null;

        public CommandAgent(IBusyService busyService, IEventAggregator eventAggregator)
        {
            this.busyService = busyService;
            this.eventAggregator = eventAggregator;
        }

        /// <summary>
        /// Occurs when the agent has finished sending one or more commands to the server.
        /// </summary>
        public event EventHandler<CommandsSentEventArgs> CommandsSent;

        public void Send(ServicedCommand command)
        {
            busyService.MarkAsBusy();

            var commands = new List<ServicedCommand> {command};

            var service = new CommandServiceClient();
            service.Endpoint.Address = new EndpointAddress(CommandServiceUri);
            service.ExecuteCompleted += OnExecuteCompleted;
            service.ExecuteAsync(new ObservableCollection<ServicedCommand>(commands), commands);
        }

        private void OnExecuteCompleted(object sender, AsyncCompletedEventArgs e)
        {
            busyService.UnmarkAsBusy();

            if (e.Error != null)
            {
                new ErrorWindow(e.Error).Show();
            }
            else
            {
                var commands = (IEnumerable<ServicedCommand>)e.UserState;

                if (CommandsSent != null)
                {
                    CommandsSent(this, new CommandsSentEventArgs(commands));
                }

                foreach (var command in commands)
                {
                    eventAggregator.Publish(command);
                }
            }
        }
    }
}